package com.red.wine.util;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.red.wine.R;
import com.red.wine.WineApp;

/**
 * TODO 字符串工具类
 */
public class StringUtil {

	/**
	 * @param str
	 * @return true-str为空  false-str不为空
	 * TODO 字符串非空判断
	 */
	public static boolean isEmptyOrNull(String str) {
		return str == null || str.length() == 0 || str.contentEquals("null")
				|| str.trim().equals("");
	}

	/**
	 * @param is
	 * @param os
	 * TODO  字符串复制
	 */
	public static void CopyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
		}
	}

	/**
	 * @param string str
	 * @param Object... args
	 * @return
	 */
	public static String format(String str, Object... args) {
		if (isEmptyOrNull(str))
			return "";
		if (args.length == 0)
			return str;
		String result = str;
		Pattern p = java.util.regex.Pattern.compile("\\{(\\d+)\\}");
		Matcher m = p.matcher(str);
		while (m.find()) {
			int index = Integer.parseInt(m.group(1));
			if (index < args.length) {
				result = result.replace(m.group(), args[index].toString());
			}
		}
		return result;
	}

	/**
	 * @return "yyyy-MM-dd HH:mm"
	 */
	public static String getReportTime() {
		SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date date = new Date(System.currentTimeMillis());
		return sfd.format(date);
	}
	
	/**
	 * 
	 * @return "yyyy-MM-dd HH:mm:ss"
	 */
	public static String getFullReportTime() {
		SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date(System.currentTimeMillis());
		return sfd.format(date);
	}
	
	/**
	 * 
	 * @return "yyyy-MM-dd"
	 */
	public static String getFormTime() {
		SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date(System.currentTimeMillis());
		return sfd.format(date);
	}

	/**
	 * @param string value
	 * @return "yyyy-mm-dd HH:mm"
	 */
	public static String getTaskTime(String value) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date date;
		try {
			date = sdf.parse(value);
			return sdf.format(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	/**
	 * 
	 * @param string value
	 * @return "yyyy-MM-dd"
	 */
	public static String getFormTaskTime(String value) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date;
		try {
			date = sdf.parse(value);
			return sdf.format(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	/**
	 * 
	 * @param long mill
	 * @return  "yyyy-MM-dd HH:mm:ss"
	 */
	public static String millToDate(Long mill) {
		SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date1 = new Date(mill);
		return sfd.format(date1);
	}

	/**
	 * @param String dateString
	 * @return long: 将字符串 "yyyy-MM-dd" 转换为以毫秒时间单位表示
	 */
	public static Long DateTomill(String dateString) {
		SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = sfd.parse(dateString);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.getTimeInMillis();
	}
	
	/**
	 * @param String dateString
	 * @return long:将字符串 "yyyy-MM-dd HH:mm" 转换为以毫秒时间单位表示
	 */
	public static Long FormDateTomill(String dateString) {
		SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date date = null;
		try {
			date = sfd.parse(dateString);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.getTimeInMillis();
	}
	
	/**
	 * @param dateString
	 * @return 将字符串 "yyyy-MM-dd HH:mm:ss" 转换为以毫秒时间单位表示
	 */
	public static Long FormDateToTime(String dateString) {
		SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = null;
		try {
			date = sfd.parse(dateString);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.getTimeInMillis();
	}

	/**
	 * @param dateString 
	 * @return 拆分后的字符串
	 */
	public static String formatDate(String dateString) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			Date date = sdf.parse(dateString);
			long now = Calendar.getInstance().getTimeInMillis();
			if (date.getTime() - now < 0) {
				return sdf.format(sdf.parse(dateString));
			} else if (DateUtils.isToday(date)) {
				sdf = new SimpleDateFormat("今天HH:mm");
				return sdf.format(date);
			} else if (DateUtils.isWithinDaysFuture(date, 1)) {
				sdf = new SimpleDateFormat("明天HH:mm");
				return sdf.format(date);
			} else if (DateUtils.isWithinDaysFuture(date, 2)) {
				sdf = new SimpleDateFormat("后天HH:mm");
				return sdf.format(date);
			} else {
				sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				return sdf.format(date);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	public static boolean isOverDue(String dateString) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			return sdf.parse(dateString).getTime() < (new Date().getTime());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public static String longToDate(long timestamp) {
		SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd");
		Date date1 = new Date(timestamp);
		return sfd.format(date1);
	}

	/**
	 * @return current time with format yyyy-MM-dd HH:mm:ss.SSS
	 */
	public static String getCurrentTime() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		Date date = new Date(System.currentTimeMillis());
		return sdf.format(date);
	}

	public static boolean isImageUrl(String imgUrl) {
		if (isEmptyOrNull(imgUrl)) {
			return false;
		}
		String regEx = "([^\\s]+(\\.(?i)(jpg|png|gif))$)";
		Pattern pattern = Pattern.compile(regEx);
		Matcher matcher = pattern.matcher(imgUrl);
		return matcher.matches();
	}

	/**
	 * 截取一段字符的长度(汉、日、韩文字符长度为2),不区分中英文 ,如果数字不正好，则少取一个字符位
	 * 
	 * @param str
	 *            原始字符串
	 * @param srcPos
	 *            开始位置
	 * @param specialCharsLength
	 *            截取长度(汉、日、韩文字符长度为2)
	 * @return
	 */
	public static String substring(String str, int srcPos,
			int specialCharsLength) {
		if (str == null || "".equals(str) || specialCharsLength < 1) {
			return "";
		}
		if (srcPos < 0) {
			srcPos = 0;
		}
		if (specialCharsLength <= 0) {
			return "";
		}
		// 获得字符串的长度
		char[] chars = str.toCharArray();
		if (srcPos > chars.length) {
			return "";
		}

		int strLength = 0;
		for (int i = 0; i < chars.length; i++) {
			strLength += getSpecialCharLength(chars[i]);
		}

		if (strLength < specialCharsLength) {
			return str;
		}
		int charsLength = getCharsLength(chars, specialCharsLength);
		return new StringBuffer()
				.append(new String(chars, srcPos, charsLength)).append("...")
				.toString();
	}

	/**
	 * 获取一段字符的长度，输入长度中汉、日、韩文字符长度为2， 输出长度中所有字符均长度为1
	 * 
	 * @param chars
	 *            一段字符
	 * @param specialCharsLength
	 *            输入长度，汉、日、韩文字符长度为2
	 * @return 输出长度，所有字符均长度为1
	 */
	private static int getCharsLength(char[] chars, int specialCharsLength) {
		int count = 0;
		int normalCharsLength = 0;
		for (int i = 0; i < chars.length; i++) {
			int specialCharLength = getSpecialCharLength(chars[i]);
			if (count <= specialCharsLength - specialCharLength) {
				count += specialCharLength;
				normalCharsLength++;
			} else {
				break;
			}
		}
		return normalCharsLength;
	}

	private static int getSpecialCharLength(char c) {
		if (isLetter(c)) {
			return 1;
		} else {
			return 2;
		}
	}

	public static boolean isLetter(char c) {
		int k = 0x80;
		return c / k == 0 ? true : false;
	}

	public static String getDomain(String url) {
		if (isEmptyOrNull(url))
			return null;
		String domain;
		try {
			int pos = url.indexOf("//");
			domain = url.substring(pos + 2);
			int endpos = domain.indexOf("/");

			if (url.indexOf("http") > -1) {
				domain = "http://" + domain.substring(0, endpos);
			} else {
				domain = "https://" + domain.substring(0, endpos);
			}
		} catch (StringIndexOutOfBoundsException e) {
			return null;
		} catch (Exception e) {
			return null;
		}
		return domain;
	}

	/**
	 * @param phoneNumber
	 * @return 是电话号码-true  不是电话号码-false
	 */
	public static boolean isPhoneNumberValid(String phoneNumber) {
		return Pattern.matches(
				"^[1]([3][0-9]{1}|50|53|55|56|57|59|58|86|87|88|89)[0-9]{8}$",
				phoneNumber);
	}

	/**
	 * @return 应用版本信息：Version + 版本号 + 时间(MMdd)
	 */
	public static String getBuildVersion() {
		SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
		Date date = new Date(System.currentTimeMillis());
		StringBuilder sb = new StringBuilder();
		sb.append("应用版本信息：Version ")
				.append(WineApp.getInstance().getResources()
						.getString(R.string.app_version)).append('.')
				.append(sdf.format(date));
		return sb.toString();
	}
	
	/**
	 * 只能输入由数字、26个英文字母或者下划线组成的字符串,且首字母、末尾字母不能是下划线
	 * @param str
	 * @return
	 */
	public static boolean isLetterDigitOrChinese(String str){
		Pattern pt = Pattern.compile("^[0-9a-zA-Z_]+$");
		Matcher mt = pt.matcher(str);
		return mt.matches();
	}
	
	/**
	 * 只能输入由数字、26个英文字母或者下划线组成的字符串,且首字母、末尾字母不能是下划线
	 * @param str
	 * @return
	 */
	public static boolean checkEmail(String email) {
		boolean flag = false;
		try {
			String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
			Pattern regex = Pattern.compile(check);
			Matcher matcher = regex.matcher(email);
			flag = matcher.matches();
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

	private static final double EARTH_RADIUS = 6378137.0;  
    
    /**
     * TODO 根据经纬度计算两点之间实际距离
     * @param longitude1
     * @param latitude1
     * @param longitude2
     * @param latitude2
     * @return 返回单位是米  
     */
    public static double getDistance(double longitude1, double latitude1,  
            double longitude2, double latitude2) {  
  
        double Lat1 = rad(latitude1);  
        double Lat2 = rad(latitude2);  
        double a = Lat1 - Lat2;  
        double b = rad(longitude1) - rad(longitude2);  
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)  
                + Math.cos(Lat1) * Math.cos(Lat2)  
                * Math.pow(Math.sin(b / 2), 2)));  
        s = s * EARTH_RADIUS;  
        s = Math.round(s * 10000) / 10000;  
        return s;  
    }  
  
    private static double rad(double d) {  
        return d * Math.PI / 180.0;  
    }  
    
    /**
     * 判断字符串是否是数字
     * @param str
     * @return
     */
    public static boolean isNumeric(String str){ 
        Pattern pattern = Pattern.compile("[0-9]*"); 
        return pattern.matcher(str).matches();    
     } 
    
    /**
	 * unicode 格式编码转换成utf-8格式编码
	 * @param theString 转换前字符串
	 * @return 转换后字符转
	 */
	public static String unicodeToUtf8(String theString) {
		char aChar;
		int len = theString.length();
		StringBuffer outBuffer = new StringBuffer(len);
		for (int x = 0; x < len;) {
			aChar = theString.charAt(x++);
			if (aChar == '\\') {
				aChar = theString.charAt(x++);
				if (aChar == 'u') {
					// Read the xxxx
					int value = 0;
					for (int i = 0; i < 4; i++) {
						aChar = theString.charAt(x++);
						switch (aChar) {
						case '0':
						case '1':
						case '2':
						case '3':
						case '4':
						case '5':
						case '6':
						case '7':
						case '8':
						case '9':
							value = (value << 4) + aChar - '0';
							break;
						case 'a':
						case 'b':
						case 'c':
						case 'd':
						case 'e':
						case 'f':
							value = (value << 4) + 10 + aChar - 'a';
							break;
						case 'A':
						case 'B':
						case 'C':
						case 'D':
						case 'E':
						case 'F':
							value = (value << 4) + 10 + aChar - 'A';
							break;
						default:
							throw new IllegalArgumentException(
									"Malformed   \\uxxxx   encoding.");
						}
					}
					outBuffer.append((char) value);
				} else {
					if (aChar == 't')
						aChar = '\t';
					else if (aChar == 'r')
						aChar = '\r';
					else if (aChar == 'n')
						aChar = '\n';
					else if (aChar == 'f')
						aChar = '\f';
					outBuffer.append(aChar);
				}
			} else
				outBuffer.append(aChar);
		}
		return outBuffer.toString();
	}

	/**
	 * unicode 编码转换为gbk格式编码
	 * @param dataStr 转换前字符串
	 * @return 转换后字字符串
	 */
	public static String unicode2GBK(String dataStr) {
		int index = 0;
		StringBuffer buffer = new StringBuffer();

		int li_len = dataStr.length();
		while (index < li_len) {
			if (index >= li_len - 1
					|| !"\\u".equals(dataStr.substring(index, index + 2))) {
				buffer.append(dataStr.charAt(index));

				index++;
				continue;
			}

			String charStr = "";
			charStr = dataStr.substring(index + 2, index + 6);

			char letter = (char) Integer.parseInt(charStr, 16);

			buffer.append(letter);
			index += 6;
		}

		return buffer.toString();
	}
}
